package pers.cnzdy.tutorial.Chapter9_Perception_Media.Section3_Audio;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

public class MusicPlayerService extends Service {
    private static final String TAG = "MusicPlayerService";
    private static final File PATH = Environment.getExternalStorageDirectory();

    public List<String> musicList;  // 存放找到的所有mp3的绝对路径。
    public MediaPlayer  player;
    public int          musicId;   // 用当前播放的歌曲在List中的下标作为Id号
    public String       musicName;

    class MusicNameFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3"));     //返回当前目录所有以.mp3结尾的文件
        }
    }

    public MusicPlayerService() {
        super();
        player = new MediaPlayer();
        musicList = new ArrayList<String>();
        try {
            File musicPath = new File(PATH, "Music");
            String[] fs = musicPath.list();
            MusicNameFilter filter = new MusicNameFilter();

            if (musicPath.listFiles(new MusicNameFilter()).length > 0) {
                for (File file : musicPath.listFiles(new MusicNameFilter())) {
                    musicList.add(file.getAbsolutePath());

                }
            }
        } catch (Exception e) {
            Log.i(TAG, "读取文件异常");
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void setPlayName(String dataSource) {
        File file = new File(dataSource);
        String name = file.getName();            // name=dd.mp3
        int index = name.lastIndexOf(".");   // 找到最后一个 .
        musicName = name.substring(0, index);    // 截取为dd
    }

    public void play() {
        try {
            player.reset();
            String dataSource = musicList.get(musicId); // 获取当前播放音乐的路径
            setPlayName(dataSource);  // 设置 musicName

            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setDataSource(dataSource); // 设置播放路径
            player.prepare();
            player.start();

            player.setOnCompletionListener(
                    new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer arg0) {
                    // 歌曲播放完毕,自动播放下一首
                    next();
                }
            });

        } catch (Exception e) {
            Log.v(TAG, e.getMessage());
        }
    }

    //继续播放
    public  void resume(){
        int position = getCurrentProgress();
        player.seekTo(position); // 恢复当前播放位置
        try {
            player.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        player.start();
    }

    public int getCurrentProgress() {
        if (player != null & player.isPlaying()) {
            return player.getCurrentPosition();
        } else if (player != null & (!player.isPlaying())) {
            return player.getCurrentPosition();
        }
        return 0;
    }

    public void next() {
        musicId = musicId == musicList.size() - 1 ? 0 : musicId + 1;
        play();
    }

    public void last() {
        musicId = musicId == 0 ? musicList.size() - 1 : musicId - 1;
        play();
    }
    // 暂停播放
    public void pause() {
        if (player != null && player.isPlaying()){
            player.pause();
        }
    }

    public void stop() {
        if (player != null && player.isPlaying()) {
            player.stop();
            player.reset();
        }
    }
}
